<template>

  <div>

    <div v-if="visible">
      <video-player :isPause="tempIsPause" v-model="file.viewUrl" :drag="course.videoDrag" :ref-id="file.fileId"
        @play="onPlay" @pause="onPause" />
    </div>

    <!-- SOCKET记录时间 -->
    <read-socket v-if="file.fileId && visible && playing" :file-id="file.fileId" :course-id="course.id"
      @change="changeLearnMin" @finish="handleFinish" @break="checkBreak" />

    <!-- 行为校验 -->
    <read-check v-if="file.fileId && visible && playing && course.checkOn" :time-min="course.checkSec"
      @break="checkBreak" />

  </div>

</template>

<script>
import VideoPlayer from '@/components/VideoPlayer'
import ReadSocket from './ReadSocket'
import ReadCheck from '@/views/web/course/components/ReadCheck'
import { watch } from 'vue'

export default {
  name: 'FilePlayer',
  components: { VideoPlayer, ReadCheck, ReadSocket },
  props: {
    course: Object,
    file: Object,
    isPause: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      tempIsPause: false,
      playing: false,
      visible: true
    }
  },

  created() {
    // 监听页面状态
    document.addEventListener('visibilitychange', this.stateChange)
  },

  watch: {
    // 监听暂停状态
    isPause: {
      immediate: true,
      handler(val) {
        if (val) {
          this.tempIsPause = true
          this.playing = false
        }
        else {
          this.tempIsPause = false
          this.playing = true
        }
      }
    },
  },

  methods: {
    // 监听面可见状态
    stateChange() {
      if (document.visibilityState === 'hidden') {
        this.visible = false
        this.$emit('pause')
      } else {
        this.visible = true
      }

      console.log('++++++video-page-visible', this.visible)
    },

    // 阅读进度变化
    changeLearnMin(data) {
      this.$emit('change', data)
    },

    // 完成课件阅读
    handleFinish(json) {
      this.$emit('finish', json)
    },

    onPlay() {
      this.playing = true
      this.$emit('play')
    },

    onPause() {
      this.playing = false
      console.log('++++++video-page-pause');

      this.$emit('pause')
    },

    // 校验超时
    checkBreak() {
      // 跳转到
      window.location = '/#/web/course?break'
    }
  }
}
</script>

<style scoped>
.file-item {

  border: #ddd 1px solid;
  text-align: left;
  padding: 10px;
  margin-bottom: 15px;
  cursor: pointer;
}

.file-item-active {

  border: #1890ff 1px solid;
  box-sizing: border-box;
  color: #1890ff;
  font-weight: 700;
}

::v-deep .content {
  text-align: left;
}

::v-deep .content img {
  text-align: left;
  max-width: 100%;
}
</style>
